//
//  ArchiveObject.m
//  Property
//
//  Created by LevinYan on 15/5/5.
//  Copyright (c) 2015年 LevinYan. All rights reserved.
//
#import <objc/runtime.h>
#import "ArchiveObject.h"

@implementation ArchiveObject

+ (instancetype)unarchiveWithPath:(NSString *)path
{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

- (void)archiveWithPath:(NSString *)path
{
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    for(NSString *property in [self allPropertyNames])
    {
        id value = [aDecoder decodeObjectForKey:property];
        [self setValue:value forKey:property];
    }
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    for(NSString *property in [self allPropertyNames])
    {
        id value = [self valueForKey:property];
        [aCoder encodeObject:value forKey:property];
    }
}
- (NSArray *)allPropertyNames
{
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    
    NSMutableArray *rv = [NSMutableArray array];
    
    for (NSUInteger i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }
    
    free(properties);
    
    return rv;
}
@end

